package ${package.Advice};

import com.github.pagehelper.PageInfo;
import ${package.Stereotype}.annotation.NotControllerResponseAdvice;
import ${package.Stereotype}.vo.LayuiTableVo;
import ${package.Stereotype}.vo.ResultVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <p>
 *  SpringBoot 全局控制器返回值处理
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@RestControllerAdvice(basePackages = {"${package.Controller}"})
public class ${table.adviceName} implements ResponseBodyAdvice<Object>{

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return !(methodParameter.getParameterType().isAssignableFrom(ResultVo.class)
            || methodParameter.hasMethodAnnotation(NotControllerResponseAdvice.class));
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(returnType.getGenericParameterType().equals(PageInfo.class))
            return new LayuiTableVo((PageInfo)data);
        if(data instanceof PageInfo)
            return new LayuiTableVo((PageInfo)data);
        if(returnType.getGenericParameterType().equals(Boolean.class))
            return (Boolean) data ? ResultVo.ok() : ResultVo.error();
        if(returnType.getGenericParameterType().equals(ResultVo.class))
            return data;
        return new ResultVo(data);
    }
}